package com.mz.mattress.admin.api.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mz.mattress.admin.common.Holder;
import com.mz.mattress.admin.entity.SysUser;
import com.mz.mattress.admin.service.SysRoleService;
import com.mz.mattress.admin.service.SysUserService;
import com.mz.mattress.api.common.Constants;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.jwt.AdminJwt;
import com.mz.mattress.api.req.UpdatePasswordReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping(Constants.ADMIN_PATH + "user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @GetMapping(value = "list")
    public Result<IPage<SysUser>> list(@RequestParam(required = false) String username,
                                       @RequestParam(required = false) String mobile,
                                       @RequestParam(required = false) String deptCode,
                                       @RequestParam(required = false) Integer status,
                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        return sysUserService.list(username, mobile, deptCode, status, pageNo, pageSize);
    }

    @GetMapping(value = "/{id}")
    public Result<SysUser> detail(@PathVariable Integer id) {
        SysUser sysUser = sysUserService.getById(id);
        return Result.ok(sysUser);
    }

    @PostMapping
    public Result add(@RequestBody SysUser sysUser) {
        return sysUserService.add(sysUser);
    }

    @PutMapping
    public Result update(@RequestBody SysUser sysUser) {
        return sysUserService.updateById(sysUser);
    }

    @DeleteMapping
    public Result delete(@RequestBody Set<Integer> ids) {
        return sysUserService.deleteByIds(ids);
    }

    @PostMapping(value = "/updatePassword")
    public Result updatePassword(@RequestBody UpdatePasswordReq req) throws Exception {
        AdminJwt adminJwt = Holder.ADMIN_JWT_THREAD_LOCAL.get();
        req.setUserId(adminJwt.getUserId());
        return sysUserService.updatePassword(req);
    }

    @GetMapping(value = "/roleIds")
    public Result<List<Integer>> roleIds(@RequestParam Integer id) {
        List<Integer> roleIds = sysRoleService.getRoleIdsByUserId(id);
        return Result.ok(roleIds);
    }

}
